package com.spring.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author panxingyu
 *
 * 保证同一个线程或者同一个事物 获取同一个连接
 */
@Component
public class ConnectionHolder {
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    @Autowired
    private DataSource dataSource;
    public Connection getConnection() throws SQLException {
        //检查当前线程是否存在连接
        Connection connection = threadLocal.get();
        if (connection == null){
            //不存在连接，获取一个
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
}
